package com.xh.hongaicodegenerator.langgraph4j.node;

import cn.hutool.core.util.StrUtil;
import com.xh.hongaicodegenerator.langgraph4j.ai.CodeQualityCheckService;
import com.xh.hongaicodegenerator.langgraph4j.ai.CodeQualityCheckServiceFactory;
import com.xh.hongaicodegenerator.langgraph4j.model.QualityResult;
import com.xh.hongaicodegenerator.langgraph4j.state.WorkflowContext;
import com.xh.hongaicodegenerator.langgraph4j.tools.CodeFileReaderTool;
import com.xh.hongaicodegenerator.monitor.FluxContext;
import com.xh.hongaicodegenerator.monitor.MonitorContextHolder;
import com.xh.hongaicodegenerator.utils.CodeValidAndFixTool;
import com.xh.hongaicodegenerator.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.bsc.langgraph4j.action.AsyncNodeAction;
import org.bsc.langgraph4j.prebuilt.MessagesState;
import java.util.ArrayList;
import java.util.List;

import static org.bsc.langgraph4j.action.AsyncNodeAction.node_async;

/**
 * 代码质量检查节点
 */
@Slf4j
public class CodeQualityCheckNode {

    public static AsyncNodeAction<MessagesState<String>> create() {
        return node_async(state -> {
            WorkflowContext context = WorkflowContext.getContext(state);
            log.info("执行节点: 代码质量检查");
            String generatedCodeDir = context.getGeneratedCodeDir();
            QualityResult qualityResult;
            try {
                // 1. 读取并拼接代码文件内容
                String codeContent = CodeFileReaderTool.readAndConcatenateCodeFiles(generatedCodeDir);
                if (StrUtil.isBlank(codeContent)) {
                    log.warn("未找到可检查的代码文件");
                    qualityResult = QualityResult.builder()
                            .isValid(false)
                            .errors(List.of("未找到可检查的代码文件"))
                            .suggestions(List.of("请确保代码生成成功"))
                            .build();
                } else {
                    // 2. 审查工具再次检查，缓解大模型幻觉的影响
                    List<String> errors = CodeValidAndFixTool.validateDirectory(generatedCodeDir,context.getGenerationType());

                    // 3. 调用 AI 进行代码质量检查
                    CodeQualityCheckServiceFactory codeQualityCheckServiceFactory = SpringContextUtil.getBean(CodeQualityCheckServiceFactory.class);
                    CodeQualityCheckService qualityCheckService = codeQualityCheckServiceFactory.createCodeQualityCheckService();
                    qualityResult = qualityCheckService.checkCodeQuality(codeContent);
                    if (errors != null && !errors.isEmpty()) {
                        qualityResult.setIsValid(false);
                        if (qualityResult.getErrors() != null) {
                            qualityResult.getErrors().addAll(errors);
                        } else {
                            qualityResult.setErrors(new ArrayList<>(errors));
                        }
                    }
                    log.info("代码质量检查完成 - 是否通过: {}", qualityResult.getIsValid());
                }
            } catch (Exception e) {
                log.error("代码质量检查异常: {}", e.getMessage(), e);
                qualityResult = QualityResult.builder()
                        .isValid(true) // 异常直接跳到下一个步骤
                        .build();
            }
            // 3. 更新状态
            context.setCurrentStep("代码质量检查");
            context.setQualityResult(qualityResult);
            Integer stepCount = context.getStepCount()+1;
            context.setStepCount(stepCount);
            FluxContext flux= MonitorContextHolder.getFlux();
            flux.getSink().next(String.format("\n\n第 %s 步 %s 执行完成\n\n",stepCount,"代码质量检查"));
            return WorkflowContext.saveContext(context);
        });
    }
}